package com.wankuma.hcm.midlet.metwit;

import METwit;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.util.Timer;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Ticker;

import net.siisise.io.BASE64;

public class UpdateThread extends Thread {

	// Constants
	private static final String urlBase = "http://twitter.com/statuses/update.xml";

	// Objects
	private Config config;
	private MainScreen mainScreen;

	// Data
	private String status;

	public UpdateThread(String status) {
		this.status = status;

		this.config = Config.getInstance();
		this.mainScreen = METwit.getMainScreen();
	}

	public synchronized void run() {
		HttpConnection c = null;
		OutputStream os = null;

		String url = urlBase;

		mainScreen.setTickerString(StringRes.UPDATING_STATUS + " \"" + status
				+ "\"");

		try {
			BASE64 b64 = new BASE64();

			c = (HttpConnection) Connector.open(url);
			c.setRequestMethod(HttpConnection.POST);
			c.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			c.setRequestProperty("Authorization", "Basic "
					+ b64
							.encode((config.getUser() + ":" + config
									.getPassword()).getBytes()));
			c.setRequestProperty("X-Twitter-Client", "METwit");

			byte[] binStatus = BinaryUtil.stringToUTFBytes(status);

			os = c.openOutputStream();
			os.write("status=".getBytes());
			os.write(UrlEncode.encode(binStatus).getBytes());
			os.write("&source=METwit".getBytes());
			os.flush();

			int code = c.getResponseCode();
			if (code == 200) {
				mainScreen.setTickerString(StringRes.HTTP_200
						+ StringRes.UPDATE_SUCCEED);
			} else if (code == 304) {
				mainScreen.setTickerString(StringRes.HTTP_304);
			} else if (code == 400) {
				mainScreen.setTickerString(StringRes.HTTP_400
						+ StringRes.API_CONTROLED);
			} else if (code == 401) {
				mainScreen.setTickerString(StringRes.HTTP_401
						+ StringRes.NOT_AUTHORIZED);
			} else {
				mainScreen.setTickerString("HTTP"
						+ new Integer(code).toString() + "."
						+ StringRes.SERVER_IS_DOWN);
			}
			mainScreen.setRemoveTickerTimer(10000);
		} catch (Exception e) {
			Alerter.alert(e.toString() + e.getMessage() + "\n");
		}
	}
}
